# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'jian.yao'

from django.db import models
from random import choice
import string
import time
charactors = string.letters + string.digits

def genRandomStr(charset, length = 8):
    return ''.join([choice(charset) for i in range(length)])

def genKey(field, length):
    def _genKey():
        key = genRandomStr(charactors, length)
        while Token.objects.filter(**{field:key}).exists():
            key = genRandomStr(charactors, length)
        return key
    return _genKey

#one month
TIMEOUT_DAYS = 30 * 24 * 60 * 60 * 1000
def calExpireTime(now = time.time(), period = TIMEOUT_DAYS):
    return now + period

class TokenManager(models.Manager):
    def create_token(self, uid, **regs):
        token = self.model(uid = uid);
        if 'last_login_ip' in regs:
            token.last_login_ip = regs['last_login_ip']
        token.save(using = self._db)
        return token

class Token(models.Model):
    uid = models.IntegerField(max_length = 16, primary_key = True, unique = True)
    token = models.CharField(max_length = 64, null = False, default = genKey('token', 8))
    createTime = models.FloatField(max_length = 32, default = time.time())
    expireTime = models.FloatField(max_length = 32, default = calExpireTime(time.time()))
    last_login_time = models.FloatField(null = True, blank = True, default = time.time())
    last_login_ip = models.CharField(max_length = 64, default = '')

    objects = TokenManager()

    class Meta:
        db_table = 'sso_token'

    def isExpired(self):
        return self.expireTime <= time.time()
